package com.linkai.controller.admin.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linkai.controller.admin.BaseController;
import com.linkai.dto.admin.business.InputOrderUpdateDto;
import com.linkai.dto.admin.business.inputOrderReback.*;
import com.linkai.entity.*;
import com.linkai.enums.R;
import com.linkai.enums.ResultDTO;
import com.linkai.service.*;
import com.linkai.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author yamon
 * @Date 2021-02-21 19:30
 * @Description 进货退货类
 * @Version 1.0
 */
@Controller
@RequestMapping("/admin/business/inputReback")
public class InputOrderRebackController extends BaseController {


    @Autowired
    private InputorderService inputorderService;

    @Autowired
    private InputorderProductService inputorderProductService;

    @Autowired
    private StorageService storageService;

    @Autowired
    private InputRebackOrderService rebackOrderService;

    @Autowired
    private InputRebackOrderProductService rebackOrderProductService;

    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("rebackOrders", rebackOrderService.listAllRebackOrder());
        modelAndView.setViewName("admin/business/inputRebackOrder/index");
        return modelAndView;
    }


    @GetMapping("/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("admin/business/inputRebackOrder/addTemp");
        return modelAndView;
    }

    @GetMapping("/listAllInputOrder")
    @ResponseBody
    public R listAllInputOrder() {
        //查找数据
        List<RebackTableIndexDto> rebackTableIndexDtos = inputorderService.listAllInputOrder4Reback();
        return R.ok().data("inputOrder", rebackTableIndexDtos);
    }

    @GetMapping("/addConnect/{id}")
    public ModelAndView addConnect(@PathVariable Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        //查找出订货单的所有商品
        InputOrderUpdateDto inputOrderUpdateDto = inputorderService.selectInputOrderDto4UpdateById(id);
        modelAndView.addObject("inputOrder", inputOrderUpdateDto);
        modelAndView.setViewName("/admin/business/inputRebackOrder/addConnect");
        return modelAndView;
    }

    /**
     * 不关联进货单添加进货退货单
     *
     * @return
     */
    @GetMapping("/addUnConnect")
    public ModelAndView addUnConnect() {
        ModelAndView modelAndView = new ModelAndView();
        //查找出订货单的所有商品
        modelAndView.setViewName("/admin/business/inputRebackOrder/addUnConnect");
        return modelAndView;
    }

    /**
     * 根据storeid获取商品列表
     *
     * @return
     */
    @GetMapping("/getProductByStore/{stoId}")
    @ResponseBody
    public R getProductByStore(@PathVariable Integer stoId) {
        final List<ProductOfUnConnectTableDto> list = storageService.listProduct4UnConnected(stoId);
        return R.ok().data("products", list);
    }


    /**
     * 关联进货单保存
     *
     * @return
     */
    @PostMapping("/connectSave/{inputOrderId}")
    @ResponseBody
    public ResultDTO<Boolean> connectSave(@PathVariable Integer inputOrderId, @RequestBody ConnectedSaveDto connectedSaveDto) {
        //对减掉对应库存量,还有总价
        final List<RebackNumberAndId> rebackProduct = connectedSaveDto.getRebackProduct();

        //保存进货退货单
        InputRebackOrder inputRebackOrder = new InputRebackOrder();
        //进货单id
        inputRebackOrder.setInputId(inputOrderId);
        inputRebackOrder.setInputOrderNumber(connectedSaveDto.getOrderId());
        inputRebackOrder.setAccId(connectedSaveDto.getAccountMoeny());
        inputRebackOrder.setBack(connectedSaveDto.getBack());
        inputRebackOrder.setBstoId(connectedSaveDto.getStoreId());
        inputRebackOrder.setInpDate(connectedSaveDto.getInputDate());
        inputRebackOrder.setEmpId(connectedSaveDto.getEmployeeId());
        inputRebackOrder.setSupplier(connectedSaveDto.getSupplier());
        inputRebackOrder.setPrice(connectedSaveDto.getPrice());
        rebackOrderService.save(inputRebackOrder);
        //保存到多表中
        for (RebackNumberAndId numberAndId : rebackProduct) {
            final InputRebackOrderProduct entity = new InputRebackOrderProduct();
            entity.setProductId(numberAndId.getId());
            entity.setInpordNum(numberAndId.getNum());
            entity.setInputRebackOrderId(inputOrderId);
            final QueryWrapper<InputorderProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_id", numberAndId.getId());
            queryWrapper.eq("input_order_id", inputOrderId);
            final InputorderProduct one = inputorderProductService.getOne(queryWrapper);
            BigDecimal bg = new BigDecimal(numberAndId.getNum());
            entity.setEachSum(bg.multiply(one.getInpordPrice()));
            entity.setInpordPrice(one.getInpordPrice());
            rebackOrderProductService.save(entity);
        }
        return super.successSaveInfo(true);
    }

    /**
     * 根据商品id、商品价格、商品供应商和仓库获取一个库存信息
     *
     * @param
     * @param inpordPrice
     * @param
     * @param proId       商品id
     * @return
     */
    private Storage getStorageByProIdAndPriceAndSupplierAndStore(Integer proId, BigDecimal inpordPrice, Integer bstoId, Integer supId) {
        //查找出来订货单对应的商品单价和商品金额
        final QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.eq("pro_id", proId);
        wrapper.eq("pro_price", inpordPrice);
        wrapper.eq("bsto_id", bstoId);
        wrapper.eq("sup_id", supId);
        return storageService.getOne(wrapper);
    }

    /**
     * 非关联商品进货退货，保存退货单
     *
     * @param rebackOrder
     * @return
     */
    @PostMapping("/unConnectSave")
    @ResponseBody
    public ResultDTO<Boolean> saveUnConnectProduct(@RequestBody UnConnectedSaveDto rebackOrder) {
        final InputRebackOrder inputRebackOrder = new InputRebackOrder();
//            inputRebackOrder.setInputId();
        inputRebackOrder.setInputOrderNumber(rebackOrder.getOrderId());
        //作为唯一标识，证明是非关联进货单
        inputRebackOrder.setSupplier(String.valueOf(-1));
        inputRebackOrder.setEmpId(rebackOrder.getEmployeeId());
        inputRebackOrder.setBstoId(rebackOrder.getStoreId());
        inputRebackOrder.setAccId(rebackOrder.getAccountMoeny());
        inputRebackOrder.setPrice(rebackOrder.getPrice());
        inputRebackOrder.setInpDate(rebackOrder.getInputDate());
        inputRebackOrder.setBack(rebackOrder.getBack());
        rebackOrderService.save(inputRebackOrder);
        //保存到多表中将商品
        for (ProductOfUnConnectTableDto product : rebackOrder.getProducts()) {
            final InputRebackOrderProduct entity = new InputRebackOrderProduct();
            entity.setInputRebackOrderId(inputRebackOrder.getId());
            entity.setProductId(storageService.getById(product.getId()).getProId());
            entity.setInpordNum(product.getProNum());
            entity.setInpordPrice(product.getProPrice());
            entity.setStorageId(product.getId());
            BigDecimal bg = new BigDecimal(product.getProNum());
            entity.setEachSum(bg.multiply(product.getProPrice()));
            entity.setSupId(storageService.getById(product.getId()).getSupId());
            rebackOrderProductService.save(entity);
        }
        return super.successSaveInfo(true);
    }

    @GetMapping("/show/{id}")
    public ModelAndView show(@PathVariable Integer id) {
        final ModelAndView modelAndView = new ModelAndView();
        final InputRebackOrder rebackOrder = rebackOrderService.getById(id);
        if (StringUtils.equals(rebackOrder.getSupplier(), "-1")) {
            //如果供应商为-1，证明是非关联进货单的账单。
            UnConnectedSaveDto unConnectedSaveDto = rebackOrderService.getOneUnConnectedDto(rebackOrder, id);
            modelAndView.addObject("item", unConnectedSaveDto);
            modelAndView.addObject("id",id);
            modelAndView.setViewName("/admin/business/inputRebackOrder/show/unConnect");
        }else{
            //关联进货单
            InputOrderUpdateDto inputOrderUpdateDto = rebackOrderService.showRebackInfo(id);
            modelAndView.addObject("inputOrder", inputOrderUpdateDto);
            modelAndView.setViewName("/admin/business/inputRebackOrder/show/connect");
        }
        return modelAndView;
    }

    /**
     * 退货，非关联
     *
     * @param id id
     * @return
     */
    @PostMapping("/outUnConnectedProduct/{id}")
    @ResponseBody
    public ResultDTO<Boolean> outUnConnectedProduct(@PathVariable Integer id) {
        //更新退货单的状态信息
        final InputRebackOrder entity = new InputRebackOrder();
        entity.setId(id);
        //表示出库成功
        entity.setInpState(1);
        rebackOrderService.updateById(entity);
        //商品也得说明出库
        //获取商品信息
        final QueryWrapper<InputRebackOrderProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("input_reback_order_id", id);
        final List<InputRebackOrderProduct> list = rebackOrderProductService.list(queryWrapper);
        List<Storage> storages = new ArrayList<>();
        List<InputRebackOrderProduct> update = new ArrayList<>();
        for (InputRebackOrderProduct rebackOrderProduct : list) {
            //商品出库
            rebackOrderProduct.setInpordState(1);
            update.add(rebackOrderProduct);
            final Storage storage = storageService.getById(rebackOrderProduct.getStorageId());
            storage.setProNum(storage.getProNum() - rebackOrderProduct.getInpordNum());
            BigDecimal bg = new BigDecimal(rebackOrderProduct.getInpordNum());
            storage.setProMoney(storage.getProMoney().subtract(bg.multiply(rebackOrderProduct.getInpordPrice())));
            storages.add(storage);
        }
        rebackOrderProductService.updateBatchById(update);
        return super.updateInfo(storageService.updateBatchById(storages));
    }


    /**
     * 退货，关联
     *
     * @param id id
     * @return
     */
    @PostMapping("/outConnectedProduct/{id}")
    @ResponseBody
    public ResultDTO<Boolean> outConnectedProduct(@PathVariable Integer id) {
        final InputRebackOrder rebackOrder = rebackOrderService.getById(id);
        final QueryWrapper<InputRebackOrderProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("input_reback_order_id", rebackOrder.getInputId());
        rebackOrder.setInpState(1);
        rebackOrderService.updateById(rebackOrder);
        final List<InputRebackOrderProduct> list = rebackOrderProductService.list(queryWrapper);
        for (InputRebackOrderProduct rebackOrderProduct : list) {
            final Inputorder inputorder = inputorderService.getById(rebackOrderProduct.getInputRebackOrderId());
            final Storage one = getStorageByProIdAndPriceAndSupplierAndStore(rebackOrderProduct.getProductId(),rebackOrderProduct.getInpordPrice(), inputorder.getBstoId(), inputorder.getSupId());
            if (one.getProNum() > rebackOrderProduct.getInpordNum()) {
                //如果库存大于退货
                storageService.updateProductNumByProId(rebackOrderProduct.getProductId(), rebackOrderProduct.getInpordNum(), rebackOrderProduct.getEachSum(), rebackOrderProduct.getInpordPrice(), inputorder.getBstoId(), inputorder.getSupId());
            } else if (rebackOrderProduct.getInpordNum() < 0) {
                return ResultDTO.errorOf(20001, "输入库存量不能小于0，请检查好数据再更新！");
            } else {
                return ResultDTO.errorOf(20001, "库存大于退货，请检查好数据再更新！");
            }
        }
        return super.updateInfo(true);
    }

}
